package com.willian.andrappfw.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.willian.andrappfw.network.WRequest;
import com.willian.andrappfw.network.RequestContext;
import com.willian.andrappfw.utils.OnClickedListener;

import java.util.ArrayList;


public abstract class BaseFragment extends Fragment implements View.OnClickListener, RequestContext {
    private final ArrayList<WRequest> mWRequestList = new ArrayList<>();
    View mContentView;
    private final int iLayoutId;
    private OnClickedListener onClickedListener;

    public abstract int getLayoutId();

    BaseFragment() {
        iLayoutId = getLayoutId();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        onClickedListener = new OnClickedListener() {
            @Override
            public void onClicked(View view) {
                BaseFragment.this.onClicked(view);
            }
        };

        if (mContentView == null && iLayoutId != 0) {
            mContentView = inflater.inflate(iLayoutId, container, false);
        } else {
            mContentView = super.onCreateView(inflater, container, savedInstanceState);
        }
        if (mContentView != null) {
            initView(mContentView);
        }

        return mContentView;
    }

    protected abstract void initView(@NonNull View contentView);

    @Override
    public void addRequest(WRequest wRequest) {
        mWRequestList.add(wRequest);
    }

    @Override
    public void removeRequest(WRequest wRequest) {
        mWRequestList.remove(wRequest);
    }

    @Override
    public void cancelAllRequests() {
        for (WRequest WRequest : mWRequestList) {
            WRequest.cancel();
        }
    }

    public abstract void onClicked(View v);

    @Override
    public final void onClick(View v) {
        onClickedListener.onClicked(v);
    }

    public void setText(int viewId, CharSequence text) {
        if (mContentView == null) {
            return;
        }
        TextView view = mContentView.findViewById(viewId);
        if (view == null) {
            return;
        }
        view.setText(text);
    }
}
